<?php
/**
 * +-------------------------------------------------------------
 * |Caption:
 * +-------------------------------------------------------------
 * |Author: Lenny
 * +-------------------------------------------------------------
 * |Email:  1685964109@qq.com
 * +-------------------------------------------------------------
 * |Date:   2024/7/30 下午2:32
 * +-------------------------------------------------------------
 */

namespace app\common\service;

use app\common\exception\BaseException;
use EasyWeChat\MiniApp\Application;
use EasyWeChat\Pay\Application as PayApplication;

class EasyWechatService
{

    /**
     * 获取小程序实例
     * @throws BaseException
     */
    public static function getApp(): Application
    {
        // 获取当前小程序信息
        $wxConfig = \app\common\service\sysConfig('wechat');
        // 验证appid和appsecret是否填写
        if (empty($wxConfig['app_id']) || empty($wxConfig['wxapp_secret'])) {
            throw new BaseException(['message' => '小程序配置信息未填写完整']);
        }
        $config = [
                'app_id' => $wxConfig['app_id'],
                'secret' => $wxConfig['wxapp_secret'],
        ];
        return new Application($config);
    }

    /**
     * 获取小程序支付实例
     * @throws BaseException
     */
    public static function getPayApp(): PayApplication
    {
        // 获取当前小程序信息
        $wxConfig = \app\common\service\sysConfig('wechat');
        // 验证appid和appsecret是否填写
        if (empty($wxConfig['mch_id'])) {
            throw new BaseException(['message' => '商户号未填写完整']);
        }
        $config = [
                'app_id'         => $wxConfig['app_id'],
                'mch_id'         => $wxConfig['mch_id'],
                // 商户证书
                'private_key'    => __DIR__ . '/certs/apiclient_key.pem',
                'certificate'    => __DIR__ . '/certs/apiclient_cert.pem',

                // v3 API 秘钥
                'secret_key'     => $wxConfig['secret_key'],

                // v2 API 秘钥
                'v2_secret_key'  => $wxConfig['v2_secret_key'],

                // 平台证书：微信支付 APIv3 平台证书，需要使用工具下载
                // 下载工具：https://github.com/wechatpay-apiv3/CertificateDownloader
                'platform_certs' => [
                        'somehow' => app_path('certs/wechatpay/wechatpay.pem')
                ],
        ];
        return new PayApplication($config);
    }
}